<template>
  <view class="address-container">
    <!-- 地址列表 -->
    <view v-for="addr in addressList" :key="addr.addressId" class="address-item">
      <!-- 编辑按钮（右上角） -->
      <view class="edit-btn" @click="() => editAddress(addr)">编辑</view>

      <!-- 第一行：省市区镇 -->
      <view class="area-line">
        {{ addr.province }} {{ addr.city }} {{ addr.district }}
      </view>

      <!-- 第二行：详细地址 -->
      <view class="detail-line">
        {{ addr.detailAddress }}
      </view>

      <!-- 第三行：姓名 + 电话 -->
      <view class="receiver-line">
        {{ addr.receiverName }} {{ addr.receiverPhone }}
      </view>

      <!-- 操作按钮：固定在右下角 -->
      <view class="actions">
        <button
          class="action-btn default-btn"
          @click="() => setDefault(addr.addressId)"
          v-if="!addr.isDefault"
        >
          使用
        </button>
        <button
          class="action-btn delete-btn"
          @click="() => deleteAddress(addr.addressId)"
        >
          删除
        </button>
      </view>
    </view>

    <!-- 占位 -->
    <view class="add-btn-placeholder"></view>
  </view>

  <!-- 固定新增按钮 -->
  <view class="fixed-add-btn-wrapper">
    <button class="add-btn" @click="navigateToAdd">新增收货地址</button>
  </view>
</template>

<script setup>
import { ref, onMounted,getCurrentInstance } from 'vue';
import { getAddressList, deleteAddress as apiDeleteAddress } from '@/api/Addressapi.js';
import userManager from '@/common/utils/user.js'
import { setDefaultAddress } from '@/api/Addressapi.js'; // 确保你有这个 API
import { onShow } from '@dcloudio/uni-app';

const { proxy } = getCurrentInstance();

// 响应式数据
const addressList = ref([]);
const userId = userManager.user.userId

// 页面加载
onShow( () => {
  const userId = userManager.user.userId
  console.log('userId:',userId);
  // userId.value = getCurrentUserInfo().id; // 假设返回 { id: xxx }
  loadAddresses();
});

// 加载地址列表
const loadAddresses = async () => {
  const list = await getAddressList(userId.value);
  addressList.value = list || [];
};

// 设为默认
const setDefault = async (addressId) => {
  const success = await setDefaultAddress(userId, addressId);
  if (success) {
    await loadAddresses(); // 刷新
	uni.$emit('addressChanged') // 触发事件通知结算页
  }
  
};

// 删除地址（带确认弹窗）
const deleteAddress = (addressId) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该收货地址吗？',
    success: async (res) => {
      if (res.confirm) {
        // 用户点击了“确定”
		console.log('addressId:',addressId);
        const success = await apiDeleteAddress(userId, addressId);
        if (success) {
          await loadAddresses(); // 刷新列表
        }
      }
      // 如果 res.cancel，什么也不做
    },
    fail: (err) => {
      console.error('弹窗调用失败', err);
    }
  });
};

// 跳转新增页面
const navigateToAdd = () => {
  uni.navigateTo({
    url: `/pages/address/address-add/address-add`
  });
};

// 跳转到编辑页面
const editAddress = (address) => {
	console.log('address：',address);
  // 将地址对象序列化为 JSON 字符串传递
  const url = `/pages/address/address-add/address-add?address=${encodeURIComponent(JSON.stringify(address))}`;
  uni.navigateTo({ url });
};

// 刷新方法，供其他页面调用
proxy.refreshAddressList = async () => {
  await loadAddresses();
};
</script>


<style scoped>
/* 页面主容器 */
.address-container {
  padding: 20rpx;
  padding-bottom: 120rpx;
}

/* 地址项 */
.address-item {
  position: relative;
  margin-bottom: 30rpx;
  border: 1px solid #eee;
  padding: 20rpx 20rpx 50rpx; /* 增加底部空间 */
  background-color: #fff;
}

.area-line {
  font-size: 24rpx;
  color: #999;
  line-height: 1.5;
  margin-bottom: 8rpx;
  white-space: normal;
  word-wrap: break-word;
}

.detail-line {
  font-size: 36rpx;
  color: #333;
  line-height: 1.4;
  margin-bottom: 12rpx;
  white-space: normal;
  word-wrap: break-word;
}

.receiver-line {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
  white-space: normal;
}

/* 操作按钮 */
.actions {
  position: absolute;
  bottom: 16rpx;
  right: 16rpx;
  display: flex;
  gap: 16rpx;
}

.action-btn {
  font-size: 24rpx;
  padding: 10rpx 16rpx;
  border-radius: 8rpx;
  line-height: 1.2;
  min-width: 0;
  height: auto;
  box-sizing: border-box;
}

.default-btn {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
}

.delete-btn {
  width: 88rpx;
  height: 56rpx;
  min-width: auto !important;
  min-height: auto !important;
  padding: 0;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ff3b30;
  color: white;
  border: none;
  border-radius: 8rpx;
  box-sizing: border-box;
}

/* 固定新增按钮 */
.fixed-add-btn-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 999;
}

.add-btn {
  width: 100%;
  background-color: red;
  color: white;
  font-size: 32rpx;
  border-radius: 8rpx;
  padding: 16rpx 0;
}

.add-btn-placeholder {
  height: 120rpx;
}

.address-item {
  position: relative;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.edit-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  font-size: 24rpx;
  color: #007aff;
  background: transparent;
  padding: 8rpx 16rpx;
  border: 1rpx solid #007aff;
  border-radius: 8rpx;
  z-index: 10;
}
</style>